<script setup name="Config" lang="ts">
import { DeleteOutlined, FormOutlined } from '@ant-design/icons-vue'
import { parseTime } from '../../../utils/ruoyi.ts'
import { addConfig, delConfig, getConfig, listConfig, refreshCache, updateConfig } from '@/api/system/config'
import type { ConfigForm, ConfigQuery, ConfigVO } from '@/api/system/config/types'

const { proxy } = getCurrentInstance() as ComponentInternalInstance
const { sys_yes_no } = toRefs<any>(proxy?.useDict('sys_yes_no'))
const message = useMessage()
const modal = useModal()
const configList = ref<ConfigVO[]>([])
const loading = ref(true)
const ids = ref<Array<number | string>>([])
const total = ref(0)
const dateRange = ref<[DateModelType, DateModelType]>(['', ''])

const queryFormRef = ref<ElFormInstance>()
const configFormRef = ref<ElFormInstance>()
const dialog = reactive<DialogOption>({
  visible: false,
  title: '',
})
const initFormData: ConfigForm = {
  configId: undefined,
  configName: '',
  configKey: '',
  configValue: '',
  configType: 'Y',
  remark: '',
}
const data = reactive<PageData<ConfigForm, ConfigQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    configName: '',
    configKey: '',
    configType: undefined,
  },
  rules: {
    configName: [{ required: true, message: '参数名称不能为空', trigger: 'blur' }],
    configKey: [{ required: true, message: '参数键名不能为空', trigger: 'blur' }],
    configValue: [{ required: true, message: '参数键值不能为空', trigger: 'blur' }],
  },
})

const { queryParams, form, rules } = toRefs(data)

/** 查询参数列表 */
async function getList() {
  loading.value = true
  const res = await listConfig(proxy?.addDateRange(queryParams.value, dateRange.value))
  configList.value = res.rows
  total.value = res.total
  loading.value = false
}

/** 取消按钮 */
function cancel() {
  reset()
  dialog.visible = false
}

/** 表单重置 */
function reset() {
  form.value = { ...initFormData }
  configFormRef.value?.resetFields()
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = ['', '']
  queryFormRef.value?.resetFields()
  handleQuery()
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  dialog.visible = true
  dialog.title = '添加参数'
}

/** 修改按钮操作 */
async function handleUpdate(row?: ConfigVO) {
  reset()
  const configId = row?.configId || ids.value[0]
  const res = await getConfig(configId)
  Object.assign(form.value, res.data)
  dialog.visible = true
  dialog.title = '修改参数'
}

/** 提交按钮 */
function submitForm() {
  configFormRef.value?.validate().then(async () => {
    form.value.configId ? await updateConfig(form.value) : await addConfig(form.value)
    message.success('操作成功')
    dialog.visible = false
    await getList()
  })
}

/** 删除按钮操作 */
async function handleDelete(row?: ConfigVO) {
  const configIds = row?.configId || ids.value
  modal.confirm({ title: `是否确认删除参数编号为"${configIds}"的数据项？`, onOk: async () => {
    await delConfig(configIds)
    await getList()
    message.success('删除成功')
  } })
}

/** 刷新缓存按钮操作 */
async function handleRefreshCache() {
  await refreshCache()
  message.success('刷新缓存成功')
}

onMounted(() => {
  getList()
})
</script>

<template>
  <div class="p-2">
    <a-card class="mb-20px">
      <div class="flex-between">
        <div>
          <a-form ref="queryFormRef" class="inline-form" :model="queryParams" layout="inline">
            <a-form-item label="参数名称" prop="configName">
              <a-input
                v-model:value="queryParams.configName" placeholder="请输入参数名称" clearable
                style="width: 240px" @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="参数键名" prop="configKey">
              <a-input
                v-model:value="queryParams.configKey" placeholder="请输入参数键名" clearable
                style="width: 240px" @keyup.enter="handleQuery"
              />
            </a-form-item>
            <a-form-item label="系统内置" prop="configType">
              <a-select
                v-model:value="queryParams.configType" style="width: 200px" placeholder="系统内置"
                allow-clear
              >
                <a-select-option v-for="dict in sys_yes_no" :key="dict.value" :label="dict.label" :value="dict.value">
                  {{ dict.label }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="mr-10px" @click="handleQuery">
                搜索
              </a-button>
              <a-button @click="resetQuery">
                重置
              </a-button>
            </a-form-item>
          </a-form>
        </div>
        <div>
          <a-row :gutter="10">
            <a-col>
              <a-button v-hasPermi="['system:config:add']" type="primary" @click="handleAdd">
                新增
              </a-button>
            </a-col>
            <a-col>
              <a-button v-hasPermi="['system:config:remove']" @click="handleRefreshCache">
                刷新缓存
              </a-button>
            </a-col>
          </a-row>
        </div>
      </div>
    </a-card>
    <a-card shadow="hover">
      <a-table :loading="loading" :pagination="false" :data-source="configList">
        <a-table-column title="参数名称" align="center" data-index="configName" :ellipsis="true" />
        <a-table-column title="参数键名" align="center" data-index="configKey" :ellipsis="true" />
        <a-table-column title="参数键值" align="center" data-index="configValue" :ellipsis="true" />
        <a-table-column title="系统内置" align="center" data-index="configType">
          <template #default="{ record }">
            <dict-tag :options="sys_yes_no" :value="record.configType" />
          </template>
        </a-table-column>
        <a-table-column title="备注" align="center" data-index="remark" :ellipsis="true" />
        <a-table-column title="创建时间" align="center" data-index="createTime" width="180">
          <template #default="{ record }">
            <span>{{ parseTime(record.createTime) }}</span>
          </template>
        </a-table-column>
        <a-table-column title="操作" align="center" width="150" class-name="small-padding fixed-width">
          <template #default="{ record }">
            <a-tooltip content="修改" placement="top">
              <a-button v-hasPermi="['system:config:edit']" type="link" @click="handleUpdate(record)">
                <FormOutlined />
              </a-button>
            </a-tooltip>
            <a-tooltip content="删除" placement="top">
              <a-button v-hasPermi="['system:config:remove']" type="link" @click="handleDelete(record)">
                <DeleteOutlined />
              </a-button>
            </a-tooltip>
          </template>
        </a-table-column>
      </a-table>
      <div class="text-right mt-20px">
        <a-pagination
          v-show="total > 0"
          v-model:current="queryParams.pageNum" v-model:pageSize="queryParams.pageSize" :total="total"
          show-less-items @change="getList"
        />
      </div>
    </a-card>

    <!-- 添加或修改参数配置对话框 -->
    <a-modal v-model:open="dialog.visible" :mask-closable="false" :keyboard="false" :title="dialog.title" width="500px" append-to-body>
      <a-form ref="configFormRef" :model="form" :rules="rules" :label-col="{ style: 'width:80px' }">
        <a-form-item label="参数名称" prop="configName">
          <a-input v-model="form.configName" placeholder="请输入参数名称" />
        </a-form-item>
        <a-form-item label="参数键名" prop="configKey">
          <a-input v-model="form.configKey" placeholder="请输入参数键名" />
        </a-form-item>
        <a-form-item label="参数键值" prop="configValue">
          <a-input v-model="form.configValue" placeholder="请输入参数键值" />
        </a-form-item>
        <a-form-item label="系统内置" prop="configType">
          <a-radio-group v-model="form.configType">
            <a-radio v-for="dict in sys_yes_no" :key="dict.value" :value="dict.value" :label="dict.value">
              {{ dict.label }}
            </a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="备注" prop="remark">
          <a-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </a-form-item>
      </a-form>
      <template #footer>
        <div class="dialog-footer">
          <a-button type="primary" @click="submitForm">
            确 定
          </a-button>
          <a-button @click="cancel">
            取 消
          </a-button>
        </div>
      </template>
    </a-modal>
  </div>
</template>
